#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/time.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
int fd;
void hand(int s)
{
    if (2==s)
    {
        //close 断开链接
        printf("bye bye\n");
        close(fd);
        exit(1);
    }
}



int main(){

    signal(2,hand);

    //创建socket
    fd = socket(AF_INET,SOCK_STREAM,0);
    if (-1==fd)
    {
        printf("创建socket失败\n");
      exit(-1);
    }
    printf("创建socket成功\n");

    //协议地址簇
    struct sockaddr_in addr={0};
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr=inet_addr("127.0.0.1");//ip地址 注意字符串转网络字节序
    addr.sin_port=htons(4556);


    //绑定
    int r = connect(fd,( struct sockaddr*)&addr,sizeof addr);

    if (-1==r)
    {
        printf("链接失败:%m\n");
        close(fd);
        exit(-1);
    }
    printf("链接成功\n");

#if 0
    //通信
    char buff[1024];
    char temp[1024];
    while (1)
    {
        printf("请输入发送给服务器的数据\n");
        scanf("%s",buff);
        r = send(fd,buff,strlen(buff),0);
        printf("发送%d字节数据到服务器\n",r);

        r = recv(fd,temp,1023,0);
        if (r >0)
        {
            temp[r] = 0;
            printf("服务器回复:%s\n",temp);
        }

    }
#else
    if (fork())
    {
        char buff[1024];
        while (1)
        {
            printf("请输入发送给服务器的数据\n");
            scanf("%s",buff);
            r = send(fd,buff,strlen(buff),0);
            printf("发送%d字节数据到服务器\n",r);

        }
    }else{
        char temp[1024];
        while (1)
        {
            r = recv(fd,temp,1023,0);
            if (r >0)
            {
                temp[r] = 0;
                printf("服务器回复:%s\n",temp);
            }

        }
    }
#endif

}